package com.dgut.interceptor;


import com.dgut.bean.Admin;
import com.dgut.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        开始前选择要放行的页面
//        1.登录页。
//        2.注册页。
//        3.导航页
        String requestURI = request.getRequestURI();
        if (requestURI.indexOf("login") != -1 || requestURI.indexOf("signup") != -1) {
            return true;
        }
////        判断用户和管理员是不是登录了
        User user = (User) request.getSession().getAttribute("user");
        Admin admin = (Admin) request.getSession().getAttribute("admin");

        if (user != null || admin != null) {
//            已登录则放行
            return true;
        } else {
//            未登录则拦截，并转发
//            重定向相当于直接访问，不能直接访问WEB-INF
//            response.sendRedirect("/WEB-INF/pages/login_test.jsp");
//            request.getRequestDispatcher("/WEB-INF/pages/test/login_test.jsp").forward(request,response);
            request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);

            return false;
        }
    }
}
